package org.neurone.userspace.dao.impl;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.neurone.domain.UserDetailInfo;
import org.neurone.domain.alter.UserInfoAlter;
import org.neurone.domain.persistence.UserDetailInfoPersistence;
import org.neurone.domain.persistence.UserInfoPersistence;
import org.neurone.userspace.dao.UserDetailDao;
import org.neurone.userspace.dao.UserInfoDao;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;

public class UserDetailDaoImpl extends BaseDaoHibernate implements UserDetailDao {
	private UserInfoDao userInfoDao;
	
	
	public UserInfoDao getUserInfoDao() {
		return userInfoDao;
	}

	public void setUserInfoDao(UserInfoDao userInfoDao) {
		this.userInfoDao = userInfoDao;
	}

	@Override
	public void addDetail(Long userID, UserDetailInfo userDetail) {
		UserInfoPersistence u = (UserInfoPersistence)this.userInfoDao.find(userID);
		if(u != null)
		{
			UserDetailInfoPersistence udp = new UserDetailInfoPersistence();

			udp.setKeyName(userDetail.getKeyName());
			udp.setKeyValue(userDetail.getKeyValue());
			udp.setBelongUser(u);

			u.getUserDetailInfoList().add(udp);
			
			getHibernateTemplate().saveOrUpdate(u);
		}
	}

	@Override
	public void deleteDetail(Long userDetailID) {
		getHibernateTemplate().delete(find(userDetailID));
	}

	@Override
	public List<UserDetailInfo> getUserDetail(final Long userID) {
		
		HibernateTemplate god = getHibernateTemplate();
		
		//由于关联列表使用了lazy加载，所以需要在统一Session下读取列表
		return (List<UserDetailInfo>)god.execute(new HibernateCallback(){

			@Override
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				
				UserInfoPersistence u= (UserInfoPersistence)session.load(UserInfoPersistence.class, userID);
				
				List<UserDetailInfo> udl = new ArrayList<UserDetailInfo>();
				for (UserDetailInfo userDetailInfo : u.getUserDetailInfoList()) {
					udl.add(userDetailInfo);
				}
				
				return udl;
			}
		});
		
	}

	@Override
	public void update(UserDetailInfo userDetail) {
		UserInfoPersistence u = (UserInfoPersistence)this.userInfoDao.find(userDetail.getBelongUser().getUserID());
		if(u != null)
		{
			UserDetailInfoPersistence udp = (UserDetailInfoPersistence)find(userDetail.getUserDetailInfoID());

			udp.setKeyName(userDetail.getKeyName());
			udp.setKeyValue(userDetail.getKeyValue());
			udp.setBelongUser(u);

			u.getUserDetailInfoList().add(udp);
			
			getHibernateTemplate().saveOrUpdate(u);
		}		
	}

	@Override
	public UserDetailInfo find(Long userDetailID) {
		return (UserDetailInfo)getHibernateTemplate().load(UserDetailInfoPersistence.class, userDetailID);
	}

}
